import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class JDBCInsert {
    public static void main(String[] args) throws SQLException {
        //第一步
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/attendance?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("123456");

        //第二步
        Connection connection = dataSource.getConnection();

        //第三步
        Scanner in = new Scanner(System.in);
        System.out.println("请输入姓名");
        String name = in.next();
        System.out.println("请分别输入学号");
        int id = in.nextInt();

        String sql = "insert into student values(?, ?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1, id); // 将第一个问号替换成 id
        statement.setString(2, name);//将第二个问号 替换成 name

        //第四部
        statement.executeUpdate();

        //第五步
        statement.close();
        connection.close();
    }
}
